#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>

#include "DetectRegions.h"
#include "OCR.h"

using namespace std;
using namespace cv;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    saveRegions = false;
    showSteps = false;
}

MainWindow::~MainWindow()
{
    delete ui;
}

string MainWindow::getFilename(string s) {

    char sep = '/';
    char sepExt='.';

    #ifdef _WIN32
        sep = '\\';
    #endif

    size_t i = s.rfind(sep, s.length( ));
    if (i != string::npos) {
        string fn= (s.substr(i+1, s.length( ) - i));
        size_t j = fn.rfind(sepExt, fn.length( ));
        if (i != string::npos) {
            return fn.substr(0,j);
        }else{
            return fn;
        }
    }else{
        return "";
    }
}


void MainWindow::on_openImageBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
            tr("Open Image"), ".", tr("Image Files (*.png *.jpg *.bmp)"));
    input_image = imread(fileName.toUtf8().data(),1);
    if(input_image.data) {

        filename_whithoutExt=getFilename(fileName.toStdString());
        cout << "working with file: "<< filename_whithoutExt << "\n";
    }
}

void MainWindow::on_applyANPRBtn_clicked()
{
    if (filename_whithoutExt.length()<4 ||  xmlFilename.length()<4 ||  ocrFilename.length()<4)
        return;
    // Detect posibles plate regions
    DetectRegions detectRegions;
    detectRegions.setFilename(filename_whithoutExt);
    detectRegions.saveRegions=saveRegions;
    detectRegions.showSteps=showSteps;
    vector<Plate> posible_regions= detectRegions.run( input_image );

    //SVM for each plate region to get valid car plates
    //Read file storage.
    FileStorage fs;
    fs.open(xmlFilename, FileStorage::READ);
    Mat SVM_TrainingData;
    Mat SVM_Classes;
    fs["TrainingData"] >> SVM_TrainingData;
    fs["classes"] >> SVM_Classes;

    //Set SVM params
    CvSVMParams SVM_params;
    SVM_params.svm_type = CvSVM::C_SVC;
    SVM_params.kernel_type = CvSVM::LINEAR;
    SVM_params.degree = 0;
    SVM_params.gamma = 1;
    SVM_params.coef0 = 0;
    SVM_params.C = 1;
    SVM_params.nu = 0;
    SVM_params.p = 0;
    SVM_params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 1000, 0.01);

    // Achtung: Training sollte eigentlich vor der Anwendung der Klassifizierung
    //          ausgefuehrt werden. In der Anwednung sollte nur predict verwendet
    //          werden!

    //Train SVM
    CvSVM svmClassifier(SVM_TrainingData, SVM_Classes, Mat(), Mat(), SVM_params);

    //For each possible plate, classify with svm if it's a plate or not
    vector<Plate> plates;
    for(int i=0; i< posible_regions.size(); i++)
    {
        Mat img=posible_regions[i].plateImg;
        Mat p= img.reshape(1, 1);
        p.convertTo(p, CV_32FC1);

        int response = (int)svmClassifier.predict( p );
        if(response==1)
            plates.push_back(posible_regions[i]);
    }

    cout << "Num plates detected: " << plates.size() << "\n";

    // For each plate detected, recognize it with OCR
    cout << "OCR XML File : " << ocrFilename << endl;
    OCR ocr(ocrFilename);

    ocr.saveSegments=true;
    ocr.DEBUG=true;
    ocr.filename=filename_whithoutExt;
    for(int i=0; i< plates.size(); i++){
        Plate plate=plates[i];

        string plateNumber=ocr.run(&plate);
        string licensePlate=plate.str();
        cout << "================================================\n";
        cout << "License plate number: "<< licensePlate << "\n";
        cout << "================================================\n";
        rectangle(input_image, plate.position, Scalar(0,0,200));
        putText(input_image, licensePlate, Point(plate.position.x, plate.position.y), CV_FONT_HERSHEY_SIMPLEX, 1, Scalar(0,0,200),2);
        if(false){
            imshow("Plate Detected seg", plate.plateImg);
            cvWaitKey(0);
        }
    }
    imshow("Plate Detected", input_image);

}

void MainWindow::on_saveRgn_toggled(bool checked)
{
    saveRegions = checked;
}

void MainWindow::on_showSteps_toggled(bool checked)
{
    showSteps = checked;
}

void MainWindow::on_openSVMBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
            tr("Open XML File for SVM"), ".", tr("XML Files (*.Xml *.XML *.xml)"));
    xmlFilename = fileName.toStdString();
}

void MainWindow::on_openOCRBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
            tr("Open XML File for OCR"), ".", tr("XML Files (*.Xml *.XML *.xml)"));
    ocrFilename = fileName.toStdString();
}
